package com.doctor.windflower_doctor.util;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;

import com.lidroid.xutils.util.LogUtils;

/**
 * <p>
 * 功能 activity 管理类
 * </p>
 * 
 * <p>
 * Copyright 北京亚普拓信息咨询服务有限公司 2014 All right reserved.
 * </p>
 * 
 * @author 皮勉 时间 2014年9月25日 上午11:28:42
 * @version 1.0 </br> 最后修改人 无
 */
public class ActivityStack {

	private final static String TAG = "ActivityHolder";
	private List<Activity> activityList = new ArrayList<Activity>();;
	private static ActivityStack instance;

	private ActivityStack() {
	}

	public static synchronized ActivityStack getInstance() {
		if (instance == null) {
			instance = new ActivityStack();
		}
		return instance;
	}

	/**
	 * add the activity in to a list end
	 * 
	 * @param activity
	 */
	public void addActivity(Activity activity) {
		try {
			if (activity != null && activityList != null) {
				int size = activityList.size();
				if (checkActivityIsVasivle(activity)) {
					removeActivity(activity);
					activityList.add(activityList.size(), activity);
				} else {
					activityList.add(activity);
				}
				size = activityList.size();
				for (int i = 0; i < size; i++) {
					LogUtils.i("addActivity ==[" + i + "]" + " " + activityList.get(i));
				}

			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/**
	 * finish all the activity in the list.
	 * 
	 * @param context
	 *            the activity calling this method hold the context
	 */
	public void finishAllActivity() {
		if (activityList != null) {
			int size = activityList.size();
			for (int i = size - 1; i >= 0; i--) {
				Activity activity = activityList.get(i);
				if (activity != null) {
					activity.finish();
				}
				LogUtils.i("finishAllActivity ==[" + i + "]" + " " + activity);
				activityList.remove(activity);
				// activityList.clear();
			}
		}

	}

	/**
	 * remove the finished activity in the list.
	 * 
	 * @param activity
	 *            the activity is removed from activityList
	 */
	public void removeActivity(Activity activity) {
		try {
			if (activityList != null) {
				activityList.remove(activity);
				LogUtils.i("removeActivity==" + " " + activity + "activityList.size===" + activityList.size());
			}
		} catch (Exception e) {
			LogUtils.e("removeActivity" + e.getMessage());
		}
	}

	public boolean checkActivityIsVasivle(Activity activity) {
		LogUtils.i(" " + activityList.contains(activity));
		return activityList.contains(activity);
	}

	/**
	 * <p>
	 * 功能 干掉除home外的所有activity
	 * </p>
	 * 
	 * @author 罗坚 时间 2013年12月11日 上午5:38:59
	 */
	public void finishWorkActivity() {
		Activity act = null;
		for (int index = 0; index < activityList.size(); index++) {
			act = activityList.remove(index);
			if (act == null) {
				continue;
			}
			// if(act.getClass()==HomeActivity.class){
			// continue;
			// }
			act.finish();
		}

	}
}
